/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.mybatis.config;

import com.google.common.collect.Lists;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 列默认值配置
 * 取值规则
 * 大小写敏感
 * 此配置 => session => 默认class
 *
 * @author Arisgo
 * @since 2024/1/21
 */
@Component
@ConfigurationProperties(value = "arisgo.cloud.mybatis")
public class ArisgoMybatisProperties {

    private List<FieldValue> columns;

    public void setColumns(List<FieldValue> columns) {
        this.columns = columns;
    }

    public List<FieldValue> getColumns() {
        return null == this.columns ? getDefaultColumns() : this.columns;
    }

    private List<FieldValue> getDefaultColumns() {
        this.columns = Lists.newArrayList();
        columns.add(new FieldValue("tenantId", "$tenantId", "INSERT"));
        columns.add(new FieldValue("createdBy", "$userId", "INSERT"));
        columns.add(new FieldValue("createdDt", "current_time", "INSERT"));
        columns.add(new FieldValue("updatedBy", "$userId", "INSERT", "UPDATE"));
        columns.add(new FieldValue("updatedDt", "current_time", "INSERT", "UPDATE"));
        columns.add(new FieldValue("isDeleted", false, "INSERT"));
        return this.columns;
    }

    @Data
    public static class FieldValue {
        /**
         * 命令配置，sql操作场景，多个操作之间以,分隔
         * 配置项参考 {@link org.apache.ibatis.mapping.SqlCommandType}
         */
        private List<String> commands;
        /**
         * 字段名
         */
        private String field;
        /**
         * 默认值
         * "$"开头取session中的属性值
         * "current_time" 获取当前系统时间，仅支持java类型
         */
        private Object value;

        public FieldValue() {
        }

        public FieldValue(String field, Object value, String... commands) {
            this.field = field;
            this.value = value;
            this.addCommands(commands);
        }

        public void addCommands(String... commands) {
            if (null == this.commands) {
                this.commands = Lists.newArrayList();
            }
            if (null != commands) {
                this.commands.addAll(Lists.newArrayList(commands));
            }
        }

    }

}
